package com.baidu.springboot_10_simpledemo.service.impl;

import com.baidu.springboot_10_simpledemo.domain.Emp;
import com.baidu.springboot_10_simpledemo.domain.PageBean;
import com.baidu.springboot_10_simpledemo.mapper.EmpMapper;
import com.baidu.springboot_10_simpledemo.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    EmpMapper mapper;

    //分页查询所有员工 + 复杂查询
    @Override
    public PageBean<Emp> findAll(PageBean<Emp> pageBean,Emp emp) {
        int currentPage = pageBean.getCurrentPage(); //获取前端传来的currentPage
        //控制上一页操作超出
        if(currentPage<1){
            currentPage=1;
        }
        int pageSize = pageBean.getPageSize(); //获取前端传来的pageSize
        //创建一个新的pageBean对象
        PageBean<Emp> pb = new PageBean<Emp>();
        //设置参数
        pb.setCurrentPage(currentPage);
        pb.setPageSize(pageSize);
        //查询总记录数，并设置到新的pb对象中
        Integer totalCount = mapper.findTotalCount(emp.getName(),emp.getGender(),emp.getDeptId());
        pb.setTotalCount(totalCount);
        //查询emp集合数据，先计算开始的索引
        int start = (currentPage-1)*pageSize;
        List<Emp> emps = mapper.findAll(start,pageSize,emp.getName(),emp.getGender(),emp.getDeptId());
        pb.setList(emps);
        //计算总页码
        int totalPage =  (totalCount % pageSize)  == 0 ? totalCount/pageSize : (totalCount/pageSize) + 1;
        pb.setTotalPage(totalPage);
        //控制下一页操作超出
        if (currentPage>=totalPage){
            currentPage=totalPage;
            pb.setCurrentPage(currentPage);
        }
        return pb;
    }
    //添加员工
    @Override
    public void addEmp(Emp emp) {
        mapper.addEmp(emp);
    }
    //根据id查询员工
    @Override
    public Emp findById(Integer id) {
        Emp emp = mapper.findById(id);
        return emp;
    }
    //修改员工
    @Override
    public void updateEmp(Emp emp) {
        mapper.updateEmp(emp);
    }
    //删除员工
    @Override
    public void deleteEmp(Integer id) {
        mapper.deleteEmp(id);
    }
    //批量删除员工
    @Override
    public void delSelected(String[] ids) {
        if(ids != null && ids.length > 0){
            //1.遍历数组
            for (String id : ids) {
                //2.调用mapper删除
                mapper.deleteEmp(Integer.parseInt(id));
            }
        }
    }


}
